package org.example;

import org.w3c.dom.Node;

public class BinaryTree {
    //定义二叉树的节点
    public static  class  BTNode{
        BTNode left;
        BTNode right;
        int value;
        BTNode(int value){
            this.value = value;
        }
    }
    private BTNode root;
    //构造函数
    public BinaryTree(){
        this.root = null;
    }
    public void createBinaryTree(){
        BTNode node1 = new BTNode(1);
        BTNode node2 = new BTNode(2);
        BTNode node3 = new BTNode(3);
        BTNode node4 = new BTNode(4);
        BTNode node5 = new BTNode(5);
        BTNode node6 = new BTNode(6);
        //设置根节点
        root=node1;
        //建立关系
        node1.left=node2;
        node1.right=node4;
        node2.left = node3;
        node4.left = node5;
        node5.right = node6;
    }
    // --- 遍历方法 ---
    // 先序遍历 (根 -> 左 -> 右)
    public void preOrderTraversal(BTNode node) {
        if (node!=null){
            System.out.print(node.value+" ");
            preOrderTraversal(node.left);
            preOrderTraversal(node.right);
        }
    }
    // 中序遍历 (左 -> 根 -> 右)
    public void inOrderTraversal(BTNode node) {
        if (node!=null){
            inOrderTraversal(node.left);
            System.out.print(node.value+" ");
            inOrderTraversal(node.right);
        }
    }
    // 后序遍历 (左 -> 右 -> 根)
    public void postOrderTraversal(BTNode node) {
        if (node != null) {
            postOrderTraversal(node.left);
            postOrderTraversal(node.right);
            System.out.print(node.value + " ");
        }
    }
    // 便捷方法：从根开始遍历
    public void preOrder() {
        preOrderTraversal(root);
        System.out.println();
    }

    public void inOrder() {
        inOrderTraversal(root);
        System.out.println();
    }

    public void postOrder() {
        postOrderTraversal(root);
        System.out.println();
    }
    public static void main(String[] args) {
        BinaryTree tree = new BinaryTree();
        tree.createBinaryTree();
        System.out.println("先序遍历：");
        tree.preOrder();
        System.out.println("中序遍历：");
        tree.inOrder();
        System.out.println("后序遍历：");
        tree.postOrder();
    }
}

